package com.gemme.gemme.shequ;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gemme.gemme.BaseActivity;
import com.gemme.gemme.R;
import com.gemme.gemme.adapter.DataBean;
import com.gemme.gemme.adapter.ImageAdapter;
import com.gemme.gemme.login.Constant;
import com.gemme.gemme.login.GlideCircleTransform;
import com.gemme.gemme.manager.DataManager;
import com.gemme.gemme.manager.DataPares;
import com.gemme.gemme.test.MyPhotoFragment;
import com.gemme.gemme.util.DpUtil;
import com.gemme.gemme.util.PCUtil;
import com.gemme.gemme.util.SPUtil;
import com.gemme.gemme.util.ShapeUtil;
import com.gemme.gemme.util.StrUtil;
import com.gemme.gemme.view.ChatDialog;
import com.gemme.gemme.view.GeneralDialog;
import com.gemme.gemme.view.OnChangeLIstener;
import com.gemme.gemme.view.Topview;
import com.gemme.gemme.wode.ShequPsonDetActivity;
import com.google.android.material.tabs.TabLayout;
import com.jaeger.library.StatusBarUtil;
import com.luck.picture.lib.PictureSelector;
import com.shuyu.gsyvideoplayer.GSYBaseActivityDetail;
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;
import com.youth.banner.Banner;
import com.youth.banner.config.IndicatorConfig;
import com.youth.banner.indicator.CircleIndicator;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class ShequDetailActivity extends Activity {
    Activity mContext = this;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //透明状态栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_shequ_detail);
        //透明导航栏
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setNavigationBarColor(Color.parseColor("#000000"));
        }

        initView();


        getDataS();

        setEditTextView();
    }




    SqDetailBean sqDetailBean;
    boolean isFocus;
    int id;
    private void getDataS() {
       try {

           id = getIntent().getIntExtra("data",-1);
           if(id < 0){
               return;
           }
           String url = DataManager.BaseUrl + "community/appccontent/details?id=" + id;

           HashMap<String, String> headMap = new HashMap<>();
           headMap.put(DataManager.AuthorizationKey,DataManager.getToken(mContext));
           DataManager.toServer2(mContext, url, DataManager.POST_TYPE, "", headMap, new DataManager.GeResponse() {
               @Override
               public void onResponse(String response) {
                   try {

                       sqDetailBean = JSON.parseObject(response, SqDetailBean.class);
                       System.out.println("");


                       SqDetailBean.DataBean data = sqDetailBean.getData();


                       String type = data.getType();
                       if("1".equals(type)) {//图片
                           banner.setVisibility(View.VISIBLE);
                           rl_video.setVisibility(View.GONE);
                           initBaaner();
                       }else{
                           banner.setVisibility(View.GONE);
                           rl_video.setVisibility(View.VISIBLE);
                           initVideo();
                       }
                       tv_nickName.setText(StrUtil.noNUll(data.getNickName()));
                       String label = StrUtil.noNUll(data.getLabel());
                       if(TextUtils.isEmpty(label)){
                           tv_title.setText(StrUtil.getTitle(data.getCdescribe()));
                       }else{
                           tv_title.setText(label);
                       }

                       tv_desc.setText(StrUtil.noNUll(data.getCdescribe()));
//                       tv_desc.setText("数码摄影中，逆光拍摄是一种既有一定拍摄难度而具有独特艺术效果的摄影手法。 拍摄时不容易表现出景物的明暗层次和线条，如果没有较为丰富的拍摄经验，就会造成曝光不准确。因此在拍摄时要熟练运用以下技巧。");
                       tv_dianzan.setText(data.getLikeCounts() + "");
                       tv_shoucang.setText(data.getCollectionCounts() + "");
                       tv_huifu.setText(data.getCommentsCounts() + "");

                       iv_dianzan.setImageResource(data.getIsLike() == 1 ? R.drawable.pc_dianzan_select
                               : R.drawable.pc_dianzan1);
                       iv_shoucang.setImageResource(data.getIsCollection() == 1 ? R.drawable.pc_collect2_select:
                               R.drawable.pc_collect2);
                       isFocus = data.getIsFocusOn() == 0? false : true;
//                       iv_head
                       changeState();
                       String headImg = data.getHeadImg();
                       if(!TextUtils.isEmpty(headImg))
//                       Glide.with(mContext).load(headImg).into( iv_head);
                           Glide.with(mContext).load(StrUtil.noNUll(headImg)).transform(new GlideCircleTransform(mContext))
                                   .into(iv_head);

                       int userId = data.getUserId();
                       String myUserId = SPUtil.getDataForString(mContext, Constant.UserId, "");

                       if(myUserId.equals(userId + "")){
                           iv_delete.setVisibility(View.VISIBLE);
                       }else{
                           iv_delete.setVisibility(View.GONE);
                       }
                   }catch (Exception e){

                   }
                   System.out.println("");
               }
           });
       }catch (Exception e){

       }
    }

    private void initVideo() {
//        sqDetailBean
        try {

            String videoPath = sqDetailBean.getData().getVideoPath();
            if (!TextUtils.isEmpty(videoPath)){
                Glide.with(mContext)
                        .setDefaultRequestOptions(
                                new RequestOptions()
                                        .frame(1000000)
                                        .centerCrop()
                        )
                        .load(videoPath)
                        .into(iv_video);
            }

            iv_video.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    PictureSelector.create(mContext).externalPictureVideo(videoPath);
                }
            });


        }catch (Exception e){

        }

    }

    private void changeState() {
        tv_guanzhu.setText(isFocus ? "已关注" : "关注");

        if (isFocus) {
            tv_guanzhu.setBackground(ShapeUtil.getCornBg(DpUtil.dip2px(this, 12.5f),"#FF9D2C2F"));
            tv_guanzhu.setTextColor(getResources().getColor(R.color.white));
        } else {
            tv_guanzhu.setBackground(ShapeUtil.setCornBgStrok(DpUtil.dip2px(this,12.5f),"#ffffffff",
                    DpUtil.dip2px(this,1f),"#FF9D2C2F"));
            tv_guanzhu.setTextColor(getResources().getColor(R.color.red));
        }
    }

    ImageView iv_head;
    TextView tv_nickName;
    TextView tv_title;
    TextView tv_desc;
    TextView tv_dianzan;
    TextView tv_shoucang;
    TextView tv_huifu;
    TextView tv_guanzhu;
    Banner banner;
    ImageView iv_video;
    ImageView iv_video_label;
    RelativeLayout rl_video;


    View ll_huifu;
    View ll_shoucang;
    View ll_dianzan;

    ImageView iv_huifu;
    ImageView iv_shoucang;
    ImageView iv_dianzan;
    ImageView iv_delete;
    private void initView() {

        banner = findViewById(R.id.banner);
        iv_video = findViewById(R.id.iv_video);
        iv_video_label = findViewById(R.id.iv_video_label);
        tv_guanzhu = findViewById(R.id.tv_guanzhu);
        tv_guanzhu.setBackground(ShapeUtil.setCornBgStrok(DpUtil.dip2px(this,12.5f),"#ffffffff",
                DpUtil.dip2px(this,1f),"#FF9D2C2F"));
        iv_head = findViewById(R.id.iv_head);
        tv_nickName = findViewById(R.id.tv_nickName);
        tv_title = findViewById(R.id.tv_title);
        tv_desc = findViewById(R.id.tv_desc);
        tv_dianzan = findViewById(R.id.tv_dianzan);
        tv_shoucang = findViewById(R.id.tv_shoucang);
        tv_huifu = findViewById(R.id.tv_huifu);
        rl_video = findViewById(R.id.rl_video);


        ll_huifu = findViewById(R.id.ll_huifu);
        ll_shoucang = findViewById(R.id.ll_shoucang);
        ll_dianzan = findViewById(R.id.ll_dianzan);

        iv_huifu = findViewById(R.id.iv_huifu);
        iv_shoucang = findViewById(R.id.iv_shoucang);
        iv_dianzan = findViewById(R.id.iv_dianzan);

        iv_delete = findViewById(R.id.iv_delete);

        ll_huifu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ChatDialog chatDialog = new ChatDialog();
                chatDialog.showDialog(mContext);
                chatDialog.setContentId(JSON.toJSONString(sqDetailBean));
            }
        });
        //关注

        tv_guanzhu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(isFocus){
                    GeneralDialog dialog = new GeneralDialog();
                    dialog.showDialog(mContext);
                    dialog.setContent("确认不再关注?");

                    dialog.getTv_confirm().setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            toGuanzhu();
                            dialog.dismisss();
                        }
                    });
                }else{
                    toGuanzhu();
                }

            }
        });

        ll_shoucang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    int isCollection = sqDetailBean.getData().getIsCollection();
                    if(isCollection == 0) {
                        shoucang();
                    }else {
                        cancelUserLike(2); //
                    }
                }catch (Exception e){

                }

//                iv_shoucang.setImageResource(R.drawable.pc_collect2_select);
            }
        });

        ll_dianzan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try{
                    int isLike = sqDetailBean.getData().getIsLike();
                    if(isLike == 0){
                        dianzan();
                    }else{
                        cancelUserLike(1);
                    }
                }catch (Exception e){

                }


//                iv_dianzan.setImageResource(R.drawable.pc_dianzan_select);
            }
        });


        iv_head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //进入社区个人中心页
                Intent intent = new Intent(mContext, ShequPsonDetActivity.class);
                intent.putExtra("data",sqDetailBean.getData().getUserId());
                startActivity(intent);
            }
        });

        iv_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                delContent();
            }
        });

        findViewById(R.id.arrow_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    //社区取消赞和取消收藏 type(1-赞  2-收藏)
    private void cancelUserLike(int type) { //
        try {

            String contentId = sqDetailBean.getData().getId() + "";
            int likeUserId = sqDetailBean.getData().getUserId();

//            47.114.162.17:9999/community/appcuserslike/cancelUserLike?type=2&likeUserId=152&contentId=47

            String url = DataManager.BaseUrl + "community/appcuserslike/cancelUserLike?" +
                    "type=" + type +
                    "&contentId=" + contentId +
                    "&likeUserId=" + likeUserId +
                    "";


            HashMap<String, String> headMap = new HashMap<>();
            headMap.put(DataManager.AuthorizationKey,DataManager.getToken(mContext));
            DataManager.toServer2(mContext, url, DataManager.POST_TYPE, "", headMap, new DataManager.GeResponse() {
                @Override
                public void onResponse(String response) {
                    System.out.println("");

                    try {
                        if(DataPares.isSucess(mContext,response)){
                            Toast.makeText(mContext, "取消成功", Toast.LENGTH_SHORT).show();
                        }else{
                            Toast.makeText(mContext, "取消失败", Toast.LENGTH_SHORT).show();
                        }
                        getDataS();
                    }catch (Exception e){

                    }
                }
            });
        }catch (Exception e){

        }

    }


    private void dianzan(){
        try {

            String userId = SPUtil.getDataForString(mContext, Constant.UserId, "");
            String type = "1";
            String contentId = sqDetailBean.getData().getId() + "";
            int likeUserId = sqDetailBean.getData().getUserId();
/*
            String url = DataManager.BaseUrl + "community/appcuserslike/saveUserLike?" +
                    "userId=" + userId +
                    "&type=" + type +
                    "&contentId=" + contentId +
                    "&likeUserId=" + likeUserId +
                    "";
*/

            String url = DataManager.BaseUrl + "community/appcuserslike/saveUserLike?" +
                    "type=" + type +
                    "&contentId=" + contentId +
                    "&likeUserId=" + likeUserId +
                    "";


            HashMap<String, String> headMap = new HashMap<>();
            headMap.put(DataManager.AuthorizationKey,DataManager.getToken(mContext));
            DataManager.toServer2(mContext, url, DataManager.POST_TYPE, "", headMap, new DataManager.GeResponse() {
                @Override
                public void onResponse(String response) {
                    System.out.println("");

                    try {
                        if(DataPares.isSucess(mContext,response)){
                            Toast.makeText(mContext, "点赞成功", Toast.LENGTH_SHORT).show();
                        }else{
                            Toast.makeText(mContext, "点赞失败", Toast.LENGTH_SHORT).show();
                        }
                        getDataS();
                    }catch (Exception e){

                    }
                }
            });
        }catch (Exception e){

        }

    }

    private void shoucang() {
        try {

            String userId = SPUtil.getDataForString(mContext, Constant.UserId, "");
            String type = "2";
            String contentId = sqDetailBean.getData().getId() + "";
            int likeUserId = sqDetailBean.getData().getUserId();
/*
            String url = DataManager.BaseUrl + "community/appcuserslike/saveUserLike?" +
                    "userId=" + userId +
                    "&type=" + type +
                    "&contentId=" + contentId +
                    "&likeUserId=" + likeUserId +
                    "";
*/

            String url = DataManager.BaseUrl + "community/appcuserslike/saveUserLike?" +
                    "type=" + type +
                    "&contentId=" + contentId +
                    "&likeUserId=" + likeUserId +
                    "";


            HashMap<String, String> headMap = new HashMap<>();
            headMap.put(DataManager.AuthorizationKey,DataManager.getToken(mContext));
            DataManager.toServer2(mContext, url, DataManager.POST_TYPE, "", headMap, new DataManager.GeResponse() {
                @Override
                public void onResponse(String response) {
                    System.out.println("");

                    try {
                        if(DataPares.isSucess(mContext,response)){
                            Toast.makeText(mContext, "收藏成功", Toast.LENGTH_SHORT).show();
                        }else{
                            Toast.makeText(mContext, "收藏失败", Toast.LENGTH_SHORT).show();
                        }
                        getDataS();
                    }catch (Exception e){

                    }
                }
            });
        }catch (Exception e){

        }

    }


    //   dataBean.setNativeimage(R.drawable.pc_shequ_detail);
    private void initBaaner() {
        try {
            ArrayList<DataBean> dataBeans = new ArrayList<>();
            List<String> pictureList = sqDetailBean.getData().getPicturePathArray();
            for (int i = 0; i < pictureList.size(); i++) {
                DataBean dataBean = new DataBean();
                dataBean.setImageRes(pictureList.get(i));
                dataBeans.add(dataBean);
            }


            ImageAdapter imageAdapter = new ImageAdapter(dataBeans);
//              .setIndicatorMargins(new IndicatorConfig.Margins(0,0,0, DpUtil.dp2px(this,50)))

            banner
//                .addBannerLifecycleObserver(this)//添加生命周期观察者
                    .setAdapter(imageAdapter)
                    .setIndicator(new CircleIndicator(this))
//                .setIndicator(new RectangleIndicator(this))
                    .isAutoLoop(false)
                    .setIndicatorNormalColor(Color.parseColor("#ff9d2c2f"))
                    .setIndicatorSelectedColor(Color.parseColor("#669D2C2F"))
                    .start()
            ;

          /*  banner.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                }
            });*/

            imageAdapter.setOnChangeLIstener(new OnChangeLIstener() {
                @Override
                public void onChangeLIstener() {
                    PCUtil.previewPic(mContext,pictureList,true);
                }
            });
        }catch (Exception e){

        }

    }


    private void toGuanzhu() {
        try {
            int userId = sqDetailBean.getData().getUserId();
            String url = DataManager.BaseUrl + "community/appcusersfans/focuson?userId=" + userId;

            HashMap<String, String> headMap = new HashMap<>();
            headMap.put(DataManager.AuthorizationKey,DataManager.getToken(mContext));
            DataManager.toServer2(mContext, url, DataManager.POST_TYPE, "", headMap, new DataManager.GeResponse() {
                @Override
                public void onResponse(String response) {
                    try {

                        getDataS();
                        String msg = (new JSONObject(response)).getString("msg");
                        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();

                    }catch (Exception e){

                    }
                    System.out.println("");
                }
            });
        }catch (Exception e){

        }

    }



    private void setEditTextView() {
        findViewById(R.id.et_search).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ChatDialog chatDialog = new ChatDialog();
                chatDialog.showDialog(mContext);
                chatDialog.setContentId(JSON.toJSONString(sqDetailBean));
            }
        });


       /* View decorView = getWindow().getDecorView();
        View contentView = findViewById(Window.ID_ANDROID_CONTENT);// 此处的控件ID可以使用界面当中的指定的任意控件
//        View contentView = findViewById(R.id.rl_edit);// 此处的控件ID可以使用界面当中的指定的任意控件
        decorView.getViewTreeObserver().addOnGlobalLayoutListener(getGlobalLayoutListener(decorView, contentView));
*/
    }

    private ViewTreeObserver.OnGlobalLayoutListener getGlobalLayoutListener(final View decorView, final View contentView) {
        return new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                decorView.getWindowVisibleDisplayFrame(r);

                int height = decorView.getContext().getResources().getDisplayMetrics().heightPixels;
                int diff = height - r.bottom;

                if (diff != 0) {
                    if (contentView.getPaddingBottom() != diff) {
                        contentView.setPadding(0, 0, 0, diff);
                    }
                } else {
                    if (contentView.getPaddingBottom() != 0) {
                        contentView.setPadding(0, 0, 0, 0);
                    }
                }
            }
        };
    }


    private void delContent() {
        String url = DataManager.BaseUrl + "community/appccontent/delContent?id=" + id;

        HashMap<String, String> headMap = new HashMap<>();
        headMap.put(DataManager.AuthorizationKey,DataManager.getToken(mContext));
        DataManager.toServer2(mContext, url, DataManager.DELETE_TYPE, "", headMap, new DataManager.GeResponse() {
            @Override
            public void onResponse(String response) {
                try {

                    getDataS();
//                    String msg = (new JSONObject(response)).getString("msg");
//                    Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
                    if(DataPares.isSucess(mContext,response)){
                        finish();
                    }
                }catch (Exception e){

                }
                System.out.println("");
            }
        });

    }

}